<?php

namespace App\Http\Controllers;

use App\Models\BlogModel;
use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use function Sodium\compare;

class registerController extends Controller
{
    //注册
    public function register(Request $request){
        if($request->isMethod('POST')) {
            $val =[
                'email' => 'required|email|unique:user',
                'username' => 'required|string',
                'password' => 'required|confirmed|string|min:6|max:15',
                'password_confirmation'=>['required'],
            ];
            $res2= $this->validate($request,[
                'captcha' => 'required|captcha'
            ]);
            if ($res2){
                if ($res = $this->validate($request, $val)){
                    $pwd = Hash::make($request->password);
                    $result = UserModel::insert(['username'=>$request->username,'password'=>$pwd,'email'=>$request->email]);
                    if ($result){
                        echo '<script>alert(\'注册成功,返回登录\');location="/index"</script>';
                    }
                }
            }
        }
    }

     //    登录
    public function login(Request $request){
        $dataa = $request->only('email','password');
        if (Auth::guard('admin')->attempt($dataa)){
//            echo '<script>alert(\'登录成功\');</script>';
//            return redirect('/obtain');
            $data = BlogModel::paginate(5);
            $user = $request->user('admin');
            $list = BlogModel::orderBy('views','desc')->take(5)->get();
//            Auth::login($user);
            // 登录并「记住」给定的用户...
//            Auth::login($user, true);
//            dd(Auth::guard('admin')->login($data));
//           return redirect('index',compact('user','data'));
            return view('index',compact('user','data','list'));
        }else{
//            使用withErrors（）返回错误信息（数组Errors），back（）表示返回提示信息,
//                  withInput()表示保留刚才输入的值（类似{{old('name)}}）
            return back()->withErrors(['用户名或者密码错误'])->withInput();
        }
    }


    //退出登录
    public function loginout(){
//        dd(Auth::user('admin'));
//                Auth::logout();
                Session()->flush();
        echo '<script>alert(\'已退出\');self.location=document.referrer;</script>';
    }

    //我的信息
    public function mine(){
        $user = Auth::guard('admin')->user();
//        dd( Auth::check());
        if ($user) {
            // 用户已经登录了...
            echo $user->email;
        }else{
            echo '未登录';
        }
    }



}
